// 存储过滤配置
let settings = {
  enableFilter: true,
  minImages: 1
};

// 过滤计数器
let filteredCount = 0;

// 加载配置
chrome.storage.sync.get({
  enableFilter: true,
  minImages: 1
}, (items) => {
  settings = items;
});

// 监听配置更新
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'SETTINGS_UPDATED') {
    settings = message.settings;
    // 重新应用过滤器
    applyFilter();
  }
});

// 检查回答是否包含足够的图片
function hasEnoughImages(answerElement) {
  const images = answerElement.querySelectorAll('img:not(.Avatar):not(.AuthorInfo-avatar)');
  return images.length >= settings.minImages;
}

// 应用过滤器
function applyFilter() {
  if (!settings.enableFilter) {
    // 如果禁用过滤，显示所有回答
    document.querySelectorAll('.List-item').forEach(item => {
      item.style.display = '';
    });
    filteredCount = 0;
    return;
  }

  // 获取所有回答
  const answers = document.querySelectorAll('.List-item');
  let hiddenCount = 0;

  answers.forEach(item => {
    const contentElement = item.querySelector('.RichContent');
    if (contentElement && !hasEnoughImages(contentElement)) {
      item.style.display = 'none';
      hiddenCount++;
    } else {
      item.style.display = '';
    }
  });

  filteredCount = hiddenCount;
  // 更新过滤计数
  chrome.runtime.sendMessage({
    type: 'UPDATE_FILTERED_COUNT',
    count: filteredCount
  });
}

// 创建MutationObserver监听页面变化
const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.addedNodes.length > 0) {
      applyFilter();
      break;
    }
  }
});

// 开始监听页面变化
observer.observe(document.body, {
  childList: true,
  subtree: true
});

// 初始应用过滤器
applyFilter();